<template>
    <div class='user'>
        <Button type="primary" @click="onAdd">添加</Button>
        <Button type="primary" @click='deletes'>删除</Button>
        <Input v-model="searchValue" class='searchInput'>
            <Button type="primary" slot="append" icon="ios-search" @click="onSearch" >搜索</Button>
        </Input>
         <Modal v-model="modal1" title="用户信息">
            <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="80">
                <FormItem label="用户名" prop="name">
                    <Input v-model="formValidate.name" placeholder="请输入姓名"></Input>
                </FormItem>
                <FormItem label="密码" prop="password">
                    <Input type="password" v-model="formValidate.password" placeholder="请输入密码"></Input>
                </FormItem>
                <FormItem label="邮箱" prop="email">
                    <Input v-model="formValidate.email" placeholder="请输入邮箱"></Input>
                </FormItem>
                <FormItem label="电话" prop="tel">
                    <Input v-model="formValidate.tel" placeholder="请输入电话"></Input>
                </FormItem>
                <FormItem>
                    <Button type="primary" @click="handleSubmit('formValidate')">提交</Button>
                    <Button type="ghost" @click="handleReset('formValidate')" style="margin-left: 8px">重置</Button>
                </FormItem>
            </Form>
        </Modal>
         <Table border :columns="columns7" :data="data6" @on-selection-change="onSelectionChange"></Table>
         <Page :total="pageCount" :page-size="pageSize" show-sizer show-elevator show-total 
         @on-change="change" @on-page-size-change="changePage"></Page>
    </div>
</template>
<script>
    import md5 from 'crypto-js/sha256';
    import {formatDate} from '../../date.js';
    export default {
        data () {
            return {
                pageCount:0,
                pageSize:10,
                history:[],
                ids:[],
                searchValue:'',
                modal1: false,
                formValidate: {
                    name: '',
                    password:'',
                    email: '',
                    tel:'',
                },
                ruleValidate: {
                    name: [
                        { required: true, message: '姓名不能为空', trigger: 'blur' }
                    ],
                    password: [
                        { required: true, message: '请填写密码', trigger: 'blur' },
                        { type: 'string', min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
                    ],
                    email: [
                        { required: true, message: '邮箱不能为空', trigger: 'blur' },
                        { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
                    ],
                    tel: [
                        { required: true, message: '手机号码不能为空', trigger: 'blur' },
                        { type: 'string', message: '手机号码格式不正确', trigger: 'blur' }
                    ],
                },
                columns7: [
                    {
                        type: 'selection',
                        width: 60,
                        align: 'center'
                    },
                    {
                        type: 'index',
                        title:'序号',
                        width:65,
                        align: 'center'
                    },
                    {
                        title: '用户名',
                        key: 'name'
                    },
                    {
                        title: '密码',
                        key: 'password'
                    },
                    {
                        title: '邮箱',
                        key: 'email'
                    },
                    {
                        title: '电话',
                        key: 'tel'
                    },
                    {
                        title: '注册时间',
                        key: 'date'
                    },
                    {
                        title: '操作',
                        key: 'action',
                        width: 200,
                        align: 'center',
                        render: (h, params) => {
                            return h('div', [
                                h('Button', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        marginRight: '5px'
                                    },
                                    on: {
                                        click: () => {
                                            this.show(params.index)
                                        }
                                    }
                                }, '查看'),
                                h('Button', {
                                    props: {
                                        size: 'small',
                                        type:'warning'
                                    },
                                    style: {
                                        marginRight: '5px'
                                    },
                                    on: {
                                        click: () => {
                                            this.onUpdate(params.row);
                                        }
                                    }
                                }, '修改'),
                                h('Button', {
                                    props: {
                                        size: 'small',
                                        type:'error'
                                    },
                                    on: {
                                        click: () => {
                                            this.confirm(params.index)
                                        }
                                    }
                                }, '删除')
                            ]);
                        }
                    }
                ],
                data6: []
            }
        },
        methods: {
            formatDate(time) {
                var date = new Date(time);
                return formatDate(date, 'yyyy-MM-dd hh:mm');
            },
            show (index) {
                this.$Modal.info({
                    title: '用户信息',
                    content: `ID：${this.data6[index]._id}<br>
                    用户名：${this.data6[index].name}<br>
                    邮箱：${this.data6[index].password}<br>
                    邮箱：${this.data6[index].email}<br>
                    电话：${this.data6[index].tel}<br>
                    出生年月：${this.data6[index].birthday}<br>
                    注册时间：${this.data6[index].date}<br>`
                })
            },
            confirm (index) {
                this.$Modal.confirm({
                    title: '警告！',
                    content: '<p>你确定要删除该用户吗</p>',
                    onOk: () => {
                        var deleteUrl='http://localhost:3000/users/data/'+this.data6[index]._id;
                        this.$http.delete(deleteUrl)
                        .then(res=>{
                            // console.log(res);
                             this.$http.post('http://localhost:3000/users/list')
                            .then(res=>{
                                this.pageCount=res.data.length;
                                this.history=res.data;
                                this.data6 = this.history.slice(0,10);
                            })
                        })
                    }
                });
            },
            change(index){
                var _start = ( index - 1 ) * this.pageSize;
                var _end = index * this.pageSize;
                this.data6 = this.history.slice(_start,_end);
            },
            changePage(q){
                this.pageSize=q;
                 this.data6 = this.history.slice(0,this.pageSize);
            },
            handleSubmit (name) {
                this.$refs[name].validate((valid) => {
                    if (valid) {
                        this.formValidate.password=md5(this.formValidate.password).toString();
                        if(this.formValidate._id&&this.formValidate._id.length>0){
                            //修改用户
                             this.$http.put(`http://localhost:3000/users/data/${this.formValidate._id}`,this.formValidate)
                            .then(res=>{
                                this.$Message.success('修改成功!');
                                this.modal1=false;
                                this.getData();
                            })
                        }else{
                            //添加新用户
                             this.$http.post('http://localhost:3000/users/data',this.formValidate)
                            .then(res=>{
                                this.$Message.success('提交成功!');
                                this.modal1=false;
                                this.getData();
                            })
                        }
                    } else {
                        this.$Message.error('表单验证失败!');
                    }
                })
            },
            handleReset (name) {
                this.$refs[name].resetFields();
            },
            onSelectionChange(selection){
                if(selection&&selection.length>0){
                    var ids=[];
                    let len=selection.length;
                    for(let i=0;i<len;i++){
                        ids.push(selection[i]._id);
                    }
                    this.ids=ids;
                }
            },
            deletes(){
                if(this.ids.length>0){
                    this.$Modal.confirm({
                        title: '警告！',
                        content: '<p>你确定要删除该用户吗</p>',
                        onOk: () => {
                            this.$http.post('http://localhost:3000/users/deletes',{idarr:this.ids.toString()})
                            .then(res=>{
                                this.$Message.info("删除数据成功");
                                this.getData();
                            })
                        }
                    });
                }else{
                    this.$Modal.warning({title: "警告！",content:"请选择要删除的数据!"});
                }
            },
            onAdd(){
                this.modal1=true;
                //对象合并，并初始表单数据
                this.$data.formValidate={};
                Object.assign(this.$data.formValidate,this.$options.data().formValidate);
            },
            onUpdate(params){
                this.modal1=true;
                Object.assign(this.$data.formValidate,params);
            },
            onSearch(){
                this.getData();
            },
            getData(){
                this.$http.post('http://localhost:3000/users/list',{name:this.searchValue})
                .then(res=>{
                    this.pageCount=res.data.length;//总条数
                    this.history=res.data;
                    this.data6 = this.history.slice(0,10);//每页要显示的条数
                    console.log(res.data);
                    for(var i=0;i<res.data.length;i++){
                        res.data[i].date=this.formatDate(res.data[i].date);
                    }
                })
            }
        },
        created(){
            this.getData();
        }
    }
</script>
<style scoped>
    .searchInput{
        width:300px;
        float:left;
    }
</style>